#include "ustfile.h"
#include "Utils.h"
#include "ustjkeys.h"
#include "tempomap.h"

#define __devloglevel__ 4

USTFile::USTFile() {}

void USTFile::handleKey(QString key, QString value) {
    (void)key;
    (void)value;
    if (_isSetting) {
        if (key == "Tempo") _tempo = QVariant(value).toFloat();
    }

    // Tempo : default value = 120.00

    if (_isNote) {
        if (key == "Length") {
            int duration = QVariant(value).toInt();
            _note[NOTE_PULSE_LENGTH] = duration;
            _note[NOTE_PULSE_OFFSET] = _posPulses;
            _posPulses += duration;
        } else if (key == "Lyric")
            _note[NOTE_LYRIC] = value;
        else if (key == "NoteNum")
            _note[NOTE_KEY_NUMBER] = QVariant(value).toInt();
        else if (key == "Intensity")
            _note[NOTE_INTENSITY] = QVariant(value).toInt();
        else if (key == "Modulation")
            _note[NOTE_MODULATION] = QVariant(value).toInt();
        else
            _note["UST:" + key] = value;
    }

    // notes:
    // Length value:480
    // Lyric value:do
    // NoteNum value:60
    // Intensity value:100
    // Modulation value:0
}

void USTFile::genSetup() {
    QJsonObject setup;

    TempoMap tmap;
    QJsonArray json;
    tmap.addTempo(0,_tempo);
    tmap.addTimeSignature(0,4,4);
    tmap.toJson(json);
    setup[TEMPOMAP] = json;
    setup[USER_AGENT] = "QTAU::USTFile";
    _ust.push_back(setup);
}

void USTFile::handleSection(QString section) {
    if (_isSetting) {
        DEVLOG_DEBUG("genSetup");
        genSetup();
    }
    if (_isNote && _note[NOTE_LYRIC] != "R") {
        if (_note[NOTE_LYRIC] == "") _note[NOTE_LYRIC] = "a";
        // do not add rests
        _ust.push_back(_note);
    }
    if (section == "#SETTING") {
        _noteCounter = -1;
        _isSetting = true;
    }
    QString number = QString("#%1").arg(_noteCounter, 4, 10, QChar('0'));
    _isNote = (number == section);
    _noteCounter++;
    if (_isNote) _isSetting = false;
}

bool USTFile::writeOutputToStream() {
    return false;
}
